﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace GoCivil.Utils
{
    /// <summary>
    /// 需要使用Unity生命周期的单例模式
    /// </summary>
    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        protected static T _instance;
        public static T Instance
        {
            get
            {
                if(_instance == null)
                {
                    _instance = FindObjectOfType<T>();
                    if(FindObjectsOfType<T>().Length > 1)
                    {
                        Debug.LogError("More than 1 !!");
                        return _instance;
                    }

                    if(_instance == null)
                    {
                        string name = typeof(T).Name;
                        Debug.Log("Instance Name : " + name);

                        GameObject instanceGO = GameObject.Find(name);
                        if(instanceGO == null)
                        {
                            instanceGO = new GameObject(name);
                        }
                        _instance = instanceGO.AddComponent<T>();

                        DontDestroyOnLoad(instanceGO);

                        Debug.Log("Add New Singleton " + _instance.name + "in Game");
                    }else
                    {
                        Debug.LogWarning("Already Exist: " + _instance.name);
                    }
                }
                return _instance;
            }
        }
    }
}
